package com.wonder.framework.service;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;
import javax.imageio.ImageIO;

import com.wonder.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.FastByteArrayOutputStream;

import com.google.code.kaptcha.Producer;
import com.wonder.common.common.AjaxMap;
import com.wonder.common.constants.Constants;
import com.wonder.framework.redis.RedisCache;
import com.wonder.common.utils.IdUtils;
import com.wonder.common.utils.sign.Base64;

@Service
public class CaptchaService {
	
	@Resource(name = "captchaProducer")
    private Producer captchaProducer;

    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath;

    @Autowired
    private RedisCache redisCache;
    
    // 验证码类型
    @Value("${wonder.captchaType}")
    private String captchaType;
    
    public Map<String,Object> Captcha() throws IOException{
    	
    	 // 保存验证码信息
        String uuid = IdUtils.simpleUUID();
        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;

        String capStr = null, code = null;
        BufferedImage image = null;

        // 生成验证码
        if ("math".equals(captchaType))
        {
            String capText = captchaProducerMath.createText();
            capStr = capText.substring(0, capText.lastIndexOf("@"));
            code = capText.substring(capText.lastIndexOf("@") + 1);
            image = captchaProducerMath.createImage(capStr);
        }
        else if ("char".equals(captchaType))
        {
            capStr = code = captchaProducer.createText();
            image = captchaProducer.createImage(capStr);
        }

        redisCache.set(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        System.out.println("验证图形码：" +verifyKey+" "+ code+"  UUID:"+uuid);
        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try
        {
            ImageIO.write(image, "jpg", os);
        }
        catch (IOException e)
        {
            return AjaxMap.failed(e.getMessage());
        }

        Map<String,Object> data=new HashMap<String,Object>();
        data.put("key", uuid);
        data.put("img", Base64.encode(os.toByteArray()));
        
        
        Map<String,Object> map=new HashMap<String,Object>();
        map.put("data", data);
        
        return map;
    	
    }

    public String validate(String captcha, String captcharef) {
        if (StringUtils.isBlank(captcha) || StringUtils.isBlank(captcharef)) {
            return "systemMessage.captchaError";

        }

        String verifyKey = Constants.CAPTCHA_CODE_KEY + captcharef;
        Object redisCaptcha = redisCache.get(verifyKey);
        if (redisCaptcha == null) {
            return "systemMessage.captchaError";

        }
        redisCache.remove(verifyKey);

        if (!redisCaptcha.toString().equals(captcha)) {
            return "systemMessage.captchaNotMatch";

        }

        return "";
    }
}
